package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuan.yblog.crud.entity.User;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.security.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author hepeiyuan on 2024/5/20 17:12
 * @description
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    IUserService iUserService;

    @Autowired
    AuthorityService authorityService;

    /**
     * 根据username从database查询用户，由 {@link org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}调用。
     * @param username the username identifying the user whose data is required.
     * @return 封装后的登录用户对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String userEmail = String.valueOf(username);
        User user = iUserService.getOne(new QueryWrapper<User>().eq("email",userEmail));
        if(user != null){
            return new LoginUser(user, authorityService.getUserAuthorities(user.getId()));
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
